package com.carkeeper.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.carkeeper.common.utils.IdWorker;
import com.carkeeper.pojo.TweetInfo;
import com.carkeeper.search.dao.TweetMapper;
import com.carkeeper.search.service.TweetService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TweetServiceImpl implements TweetService {

    @Autowired
    private TweetMapper tweetMapper;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 添加推文
     *
     * @param tweetInfo
     */
    @Override
    public void add(TweetInfo tweetInfo) {
        long id = idWorker.nextId();
        tweetInfo.setId(String.valueOf(id));
        tweetInfo.setCreateTime(new Date());
        tweetInfo.setUpdateTime(new Date());
        tweetMapper.save(tweetInfo);
        //将推文发到首页通知交换机中
        rabbitTemplate.convertAndSend("home_page_inform_exchange","",JSON.toJSONString(tweetInfo));
    }
    /**
     * 修改推文
     *
     * @param tweetInfo
     */
    @Override
    public void edit(TweetInfo tweetInfo) {

        tweetInfo.setUpdateTime(new Date());
        tweetMapper.save(tweetInfo);
    }
    /**
     * 查询
     *
     * @return
     */
    @Override
    public Map search(Map map) {
        Map<String, Object> resultMap = new HashMap<>();
        if (map != null) {
            //创建构建器
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            //创建查询条件拼接构造器
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //推文名称过滤
            if (StringUtils.isNotEmpty((String) map.get("name"))) {
                boolQueryBuilder.filter(QueryBuilders.matchQuery("name", map.get("name")));
            }
            //总类别过滤
            if (StringUtils.isNotEmpty((String) map.get("category"))) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("category", map.get("category")));
            }
            //一级类别过滤
            if (StringUtils.isNotEmpty((String) map.get("category1"))) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("category1", map.get("category1")));
            }
            //二级类别过滤
            if (StringUtils.isNotEmpty((String) map.get("category2"))) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("category2", map.get("category2")));
            }
            //添加查询条件
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            //分页查询
            String pageNum = (String) map.get("pageNum");
            String pageSize = (String) map.get("pageSize");
            if (pageNum == null) {
                pageNum = "1";
            }
            if (pageSize == null) {
                pageSize = "5";
            }
            PageRequest pageRequest = PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize));
            nativeSearchQueryBuilder.withPageable(pageRequest);
            AggregatedPage<TweetInfo> infos = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), TweetInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    ArrayList list1 = new ArrayList();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            TweetInfo tweetInfo = JSON.parseObject(hit.getSourceAsString(), TweetInfo.class);
                            list1.add(tweetInfo);
                        }
                    }
                    return new AggregatedPageImpl(list1, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            resultMap.put("list", infos.getContent());
            //返回总记录数
            resultMap.put("total", infos.getTotalElements());
            //返回总页数
            resultMap.put("totalPage", infos.getTotalPages());
            //封装页码
            resultMap.put("pageNum", pageNum);
        }

        return resultMap;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public TweetInfo findById(String id) {
        Optional<TweetInfo> optional = tweetMapper.findById(id);

        return optional.get();
    }
    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        tweetMapper.deleteById(id);
    }

}
